package com.demo;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class ClickEventDemo extends Application {

    @Override
    public void start(Stage primaryStage) {
        WebView webView = new WebView();
        WebEngine webEngine = webView.getEngine();

        // 设置HTML内容
        String htmlContent = "<html><body contenteditable='true'></body></html>";

        // 加载HTML内容
        webEngine.loadContent(htmlContent);

        // 在页面加载完成后执行JavaScript
        webEngine.getLoadWorker().stateProperty().addListener((obs, oldState, newState) -> {
            if (newState == javafx.concurrent.Worker.State.SUCCEEDED) {
                System.out.println("HTML内容已加载");
                addClickEventListener(webEngine);
            }
        });

        StackPane root = new StackPane(webView);
        Scene scene = new Scene(root, 400, 400);

        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void addClickEventListener(WebEngine webEngine) {
        // 使用JavaScript监听WebView的点击事件，并创建一个新的<p>标签
        webEngine.executeScript("function addClickEventListener() {"
                + "document.body.addEventListener('click', function(event) {"
                + "  var p = document.createElement('p');"
                + "  p.contentEditable = 'true';"
                + "  document.body.appendChild(p);"
                + "  var range = document.createRange();"
                + "  range.selectNodeContents(p);"
                + "  range.collapse(true);"
                + "  var sel = window.getSelection();"
                + "  sel.removeAllRanges();"
                + "  sel.addRange(range);"
                + "});"
                + "}"
                + "addClickEventListener();");
    }

    public static void main(String[] args) {
        launch(args);
    }
}